package com.tangsm.spring.boot.validation.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * HTTP Servlet 辅助工具类
 *
 * @author tangsm
 */
public class HttpServletUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpServletUtils.class);

    /**
     * 获取Body参数字符串
     *
     * @param request 当前的HTTP请求
     * @return Body参数
     */
    public static String getBodyStr(HttpServletRequest request) {
        String bodyStr = "";
        try {
            bodyStr = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("获取Body参数异常", e);
        }
        return bodyStr;
    }

    /**
     * 获取Body参数字符串
     *
     * @param request 当前的HTTP请求
     * @return Body参数
     */
    public static byte[] getBody(HttpServletRequest request) {
        try {
            return StreamUtils.copyToByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("获取Body参数异常", e);
        }
        return null;
    }

    /**
     * 获取请求参数字符串
     * @param request 当前的 HTTP 请求
     * @return 请求参数字符串
     */
    public static String getRequestParam(HttpServletRequest request) {
        // 获取请求参数
        Map<String, String[]> parameterMap =  request.getParameterMap();
        Set<Map.Entry<String,String[]>> entry = parameterMap.entrySet();

        Map<String, String> reqMap = new HashMap<>();
        for (Map.Entry<String, String[]> me : entry) {
            String key = me.getKey();
            String value = me.getValue()[0];
            reqMap.put(key, value);
        }
        return JsonUtils.toStringJson(reqMap);
    }
}
